package org.ricks.utils;

import org.ricks.log.Logger;

import java.io.File;
import java.io.FileFilter;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author chenwei
 * @Title:
 * @Package
 * @Description:
 * @date 2020/8/717:30
 */
public class PackageUtils {

    /**
     * 获取某个包下的所有类
     * */
    public static Set<Class<?>> getClasses(String packageName) {
        Set<Class<?>> classSet = new HashSet<>();
        try {
//            Enumeration<URL> urls = new URLClassLoader(new URL[],Thread.currentThread().getContextClassLoader()).getResources(packageName.replace(".", "/"));
            Enumeration<URL> urls = ClassUtil.getDefaultClassLoader().getResources(packageName.replace(".", "/"));
            doScanClasses(urls,classSet,packageName);
        } catch (Exception e){
            Logger.error(e.getMessage());
        }
        return classSet;
    }

    private static void doScanClasses(Enumeration<URL> urls,Set<Class<?>> classSet,String packageName){
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            String protocol = url.getProtocol();
            if ("file".equals(protocol)) {
                String packagePath = url.getPath().replaceAll("%20", " ");
                addClass(classSet, packagePath, packageName);
            } else if ("jar".equals(protocol)) {
                scanJarClasses(url,classSet,packageName);
            }
        }
    }

    public static void scanJarClasses( URL url,Set<Class<?>> classSet,String packageName){
        Enumeration<JarEntry> jarEntries = null;
        try {
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            if (jarURLConnection == null) return;
            JarFile jarFile = jarURLConnection.getJarFile();
            if (jarFile == null) return;
            jarEntries = jarFile.entries();
        } catch (Exception e) {
            Logger.error(e.getMessage());
        }
        doScanJarClasses(jarEntries,classSet,packageName);
    }

    public static void doScanJarClasses(Enumeration<JarEntry> jarEntries,Set<Class<?>> classSet,String packageName){
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (jarEntryName.endsWith(".class")) {
                String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                if(className.indexOf(packageName) == 0) {
                    doAddClass(classSet, className);
                }
            }
        }
    }

    private static void doAddClass(Set<Class<?>> classSet, String className) {
        Class<?> cls = ClassUtil.loadClass(className, false);
        classSet.add(cls);
    }

    private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
            }
        });

        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (!StrUtil.isBlank(packageName)) {
                    className = packageName + "." + className;
                }
                // 如果类名中有"$"不计算在内
                if (-1 != className.lastIndexOf("$")) {
                    continue;
                }
                doAddClass(classSet, className);
            } else {
                String subPackagePath = fileName;
                if (!StrUtil.isBlank(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if (!StrUtil.isBlank(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass(classSet, subPackagePath, subPackageName);
            }
        }
    }
}

